import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Table,
  Button,
  Space,
  Typography,
  Tag,
  Avatar,
  Modal,
  Form,
  Input,
  Select,
  message,
  Tabs,
  Popconfirm,
  Tooltip,
  Badge,
  Dropdown,
  Menu,
} from 'antd';
import {
  UserOutlined,
  TeamOutlined,
  MailOutlined,
  PlusOutlined,
  CrownOutlined,
  SettingOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import type { TabsProps } from 'antd';
import { teamApi } from '../services/api';

// 定义团队角色类型
export type TeamMemberRole = 'PL' | 'SE' | 'MDE';

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

interface TeamMember {
  membershipId: string;
  teamId: string;
  userId: string;
  name: string;
  email: string;
  avatarUrl?: string;
  role: TeamMemberRole;
  status: string;
  joinedAt: string;
  invitedBy?: string;
  permissions?: {
    canView: boolean;
    canEdit: boolean;
    canManageMembers: boolean;
    canDelete: boolean;
    canManageAnalysis: boolean;
  };
}

interface TeamInvitation {
  invitationId: string;
  teamId: string;
  invitedEmail: string;
  invitedBy: string;
  invitedByName?: string;
  role: TeamMemberRole;
  status: 'PENDING' | 'ACCEPTED' | 'REJECTED' | 'EXPIRED';
  expiresAt: string;
  createdAt: string;
}

interface TeamDetail {
  teamId: string;
  name: string;
  description?: string;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
  stats?: {
    memberCount: number;
    telemetryPointCount: number;
    extractionCount: number;
  };
  userRole?: string;
  permissions?: {
    canView: boolean;
    canEdit: boolean;
    canManageMembers: boolean;
    canDelete: boolean;
    canManageAnalysis: boolean;
  };
}

const TeamDetailPage: React.FC = () => {
  const { teamId } = useParams<{ teamId: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [team, setTeam] = useState<TeamDetail | null>(null);
  const [members, setMembers] = useState<TeamMember[]>([]);
  const [invitations, setInvitations] = useState<TeamInvitation[]>([]);
  const [activeTab, setActiveTab] = useState('members');
  const [inviteModalVisible, setInviteModalVisible] = useState(false);
  const [addMemberModalVisible, setAddMemberModalVisible] = useState(false);
  const [editMemberModalVisible, setEditMemberModalVisible] = useState(false);
  const [editingMember, setEditingMember] = useState<TeamMember | null>(null);

  const [inviteForm] = Form.useForm();
  const [addMemberForm] = Form.useForm();
  const [editMemberForm] = Form.useForm();

  // 加载团队详情
  const loadTeamDetail = async () => {
    if (!teamId) return;

    try {
      setLoading(true);
      const response = await teamApi.getTeam(teamId);
      if (response) {
        // Transform API response to match TeamDetail interface
        const transformedTeam: TeamDetail = {
          teamId: response.id,
          name: response.name,
          description: response.description,
          createdBy: response.created_by,
          createdAt: response.created_at,
          updatedAt: response.updated_at,
          stats: {
            memberCount: response.member_count,
            telemetryPointCount: 0, // TODO: Get from API
            extractionCount: 0, // TODO: Get from API
          },
          // 暂时给所有用户完整权限，后续可以实现真实的权限控制
          userRole: 'PL' as TeamMemberRole,
          permissions: {
            canView: true,
            canEdit: true,
            canManageMembers: true,
            canDelete: true,
            canManageAnalysis: true,
          }
        };
        setTeam(transformedTeam);
      }
    } catch (error: any) {
      console.error('Failed to load team detail:', error);
      if (error.response?.status === 404) {
        message.error('团队不存在');
        navigate('/teams');
      } else {
        message.error('加载团队信息失败');
      }
    } finally {
      setLoading(false);
    }
  };

  // 加载团队成员
  const loadTeamMembers = async () => {
    if (!teamId) return;

    try {
      const response = await teamApi.getTeamMembers(teamId);
      const transformedMembers = response.map(member => ({
        membershipId: member.id,
        teamId: member.team_id,
        userId: member.user_id,
        name: member.user.name,
        email: member.user.email,
        avatarUrl: member.user.avatar_url,
        role: member.role as TeamMemberRole,
        status: member.status,
        joinedAt: member.joined_at,
      }));
      setMembers(transformedMembers);
    } catch (error: any) {
      console.error('Failed to load team members:', error);
      message.error('加载团队成员失败');
    }
  };

  // 加载邀请列表
  const loadInvitations = async () => {
    // TODO: Implement team invitations API endpoint
    setInvitations([]);
  };

  useEffect(() => {
    loadTeamDetail();
  }, [teamId]);

  useEffect(() => {
    // 加载团队成员
    if (teamId) {
      loadTeamMembers();
    }
  }, [teamId]);

  // 邀请成员
  const handleInviteMember = async (values: any) => {
    // TODO: Implement team invitation API endpoint
    message.info('邀请功能暂未实现');
  };

  // 删除团队
  const handleDeleteTeam = async () => {
    if (!team) return;

    Modal.confirm({
      title: '删除团队',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>确定要删除团队 <strong>{team.name}</strong> 吗？</p>
          <p style={{ color: '#ff4d4f', fontSize: '12px' }}>
            ⚠️ 此操作不可撤销，团队所有数据将被永久删除！
          </p>
        </div>
      ),
      okText: '确定删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await teamApi.deleteTeam(team.teamId);
          message.success('团队删除成功');
          navigate('/teams');
        } catch (error: any) {
          console.error('Delete team failed:', error);
          message.error(error.response?.data?.detail || '删除团队失败');
        }
      },
    });
  };

  // 添加成员
  const handleAddMember = async (values: any) => {
    if (!teamId) return;

    try {
      await teamApi.addTeamMember(teamId, values);
      message.success('成员添加成功');
      setAddMemberModalVisible(false);
      addMemberForm.resetFields();
      loadTeamMembers(); // 重新加载成员列表
    } catch (error: any) {
      console.error('Add member failed:', error);
      message.error(error.response?.data?.detail || '添加成员失败');
    }
  };

  // 更新成员角色
  const handleUpdateMemberRole = async (values: any) => {
    if (!teamId || !editingMember) return;

    try {
      await teamApi.updateTeamMemberRole(teamId, editingMember.userId, values.role);
      message.success('成员角色更新成功');
      setEditMemberModalVisible(false);
      setEditingMember(null);
      editMemberForm.resetFields();
      loadTeamMembers(); // 重新加载成员列表
    } catch (error: any) {
      console.error('Update member role failed:', error);
      message.error(error.response?.data?.detail || '更新成员角色失败');
    }
  };

  // 移除成员
  const handleRemoveMember = async (member: TeamMember) => {
    Modal.confirm({
      title: '移除成员',
      icon: <ExclamationCircleOutlined />,
      content: `确定要移除成员 ${member.name} 吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        if (!teamId) return;

        try {
          await teamApi.removeTeamMember(teamId, member.userId);
          message.success('成员移除成功');
          loadTeamMembers(); // 重新加载成员列表
        } catch (error: any) {
          console.error('Remove member failed:', error);
          message.error(error.response?.data?.detail || '移除成员失败');
        }
      },
    });
  };

  // 获取角色标签
  const getRoleTag = (role: TeamMemberRole) => {
    const roleConfig: Record<TeamMemberRole, { color: string; icon: React.ReactNode; text: string }> = {
      PL: { color: 'purple', icon: <CrownOutlined />, text: 'PL' },
      SE: { color: 'blue', icon: <SettingOutlined />, text: 'SE' },
      MDE: { color: 'green', icon: <UserOutlined />, text: 'MDE' },
    };

    const config = roleConfig[role as TeamMemberRole];
    if (!config) return null;

    return (
      <Tag color={config.color} icon={config.icon}>
        {config.text}
      </Tag>
    );
  };

  // 获取邀请状态标签
  const getInvitationStatusTag = (status: string) => {
    const statusConfig = {
      PENDING: { color: 'processing', text: '待处理' },
      ACCEPTED: { color: 'success', text: '已接受' },
      REJECTED: { color: 'error', text: '已拒绝' },
      EXPIRED: { color: 'default', text: '已过期' },
    };

    const config = statusConfig[status as keyof typeof statusConfig];
    if (!config) return null;

    return (
      <Badge
        status={config.color as any}
        text={config.text}
      />
    );
  };

  // 成员操作菜单
  const getMemberActionMenu = (member: TeamMember) => {
    // 暂时移除权限控制，显示所有操作菜单
    // if (!team?.permissions?.canManageMembers) return null;

    const menu = (
      <Menu>
        <Menu.Item
          key="edit"
          icon={<EditOutlined />}
          onClick={() => {
            setEditingMember(member);
            editMemberForm.setFieldsValue({ role: member.role });
            setEditMemberModalVisible(true);
          }}
        >
          修改角色
        </Menu.Item>
        {member.role !== 'PL' && (
          <Menu.Item
            key="remove"
            icon={<DeleteOutlined />}
            danger
          >
            <Popconfirm
              title="移除成员"
              description={`确定要移除成员 ${member.name} 吗？`}
              onConfirm={() => handleRemoveMember(member)}
              okText="确定"
              cancelText="取消"
            >
              移除成员
            </Popconfirm>
          </Menu.Item>
        )}
      </Menu>
    );

    return (
      <Dropdown overlay={menu} trigger={['click']}>
        <Button type="text" icon={<MoreOutlined />} size="small" />
      </Dropdown>
    );
  };

  // 成员列表表格列
  const memberColumns: ColumnsType<TeamMember> = [
    {
      title: '成员',
      key: 'member',
      render: (_, record) => (
        <Space>
          <Avatar
            src={record.avatarUrl}
            icon={<UserOutlined />}
            size="small"
          />
          <div>
            <div style={{ fontWeight: 500 }}>{record.name}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>
              {record.email}
            </div>
          </div>
        </Space>
      ),
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 120,
      render: (role) => getRoleTag(role),
    },
    {
      title: '加入时间',
      dataIndex: 'joinedAt',
      key: 'joinedAt',
      width: 120,
      render: (text) => new Date(text).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'actions',
      width: 80,
      render: (_, record) => getMemberActionMenu(record),
    },
  ];

  // 邀请列表表格列
  const invitationColumns: ColumnsType<TeamInvitation> = [
    {
      title: '邀请邮箱',
      dataIndex: 'invitedEmail',
      key: 'invitedEmail',
      render: (email) => (
        <Space>
          <MailOutlined />
          <Text>{email}</Text>
        </Space>
      ),
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 120,
      render: (role) => getRoleTag(role),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => getInvitationStatusTag(status),
    },
    {
      title: '邀请者',
      dataIndex: 'invitedByName',
      key: 'invitedByName',
      render: (_, record) => record.invitedByName || record.invitedBy,
    },
    {
      title: '邀请时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (text) => new Date(text).toLocaleDateString(),
    },
    {
      title: '过期时间',
      dataIndex: 'expiresAt',
      key: 'expiresAt',
      width: 120,
      render: (text) => new Date(text).toLocaleDateString(),
    },
  ];

  if (!team) {
    return <div>加载中...</div>;
  }

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto', padding: '24px' }}>
      {/* 团队基本信息 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Space size="large">
              <Avatar size={64} icon={<TeamOutlined />} />
              <div>
                <Title level={2} style={{ margin: 0 }}>
                  {team.name}
                </Title>
                {team.description && (
                  <Text type="secondary">{team.description}</Text>
                )}
                <div style={{ marginTop: '8px' }}>
                  {getRoleTag(team.userRole as TeamMemberRole)}
                </div>
              </div>
            </Space>
          </Col>
          <Col>
            <Space>
              {/* 暂时移除权限控制，显示所有管理按钮 */}
              <Button
                icon={<EditOutlined />}
                onClick={() => navigate(`/teams/${teamId}/settings`)}
              >
                团队设置
              </Button>
              <Button
                danger
                icon={<DeleteOutlined />}
                onClick={handleDeleteTeam}
              >
                删除团队
              </Button>
              <Button onClick={() => navigate('/teams')}>
                返回列表
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="团队成员"
              value={team.stats?.memberCount || 0}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="遥测点"
              value={team.stats?.telemetryPointCount || 0}
              prefix={<TeamOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="提取任务"
              value={team.stats?.extractionCount || 0}
              prefix={<TeamOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃成员"
              value={members.filter(m => m.status === 'ACTIVE').length}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 详细信息标签页 */}
      <Card>
        <div style={{ marginBottom: '16px' }}>
          <Title level={3}>团队成员管理</Title>
          {/* 暂时移除权限控制，显示添加成员按钮 */}
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setAddMemberModalVisible(true)}
          >
            添加成员
          </Button>
        </div>
        <Table
          columns={memberColumns}
          dataSource={members}
          rowKey="membershipId"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 添加成员对话框 */}
      <Modal
        title="添加团队成员"
        open={addMemberModalVisible}
        onCancel={() => {
          setAddMemberModalVisible(false);
          addMemberForm.resetFields();
        }}
        footer={null}
      >
        <Form
          form={addMemberForm}
          layout="vertical"
          onFinish={handleAddMember}
        >
          <Form.Item
            label="用户名字"
            name="user_name"
            rules={[
              { required: true, message: '请输入用户名字' },
              { min: 1, message: '用户名字不能为空' },
            ]}
          >
            <Input placeholder="请输入要添加的用户名字" />
          </Form.Item>

          <Form.Item
            label="角色"
            name="role"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="请选择角色">
              <Option value="PL">PL</Option>
              <Option value="SE">SE</Option>
              <Option value="MDE">MDE</Option>
            </Select>
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button
                onClick={() => {
                  setAddMemberModalVisible(false);
                  addMemberForm.resetFields();
                }}
              >
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                添加成员
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改成员角色对话框 */}
      <Modal
        title="修改成员角色"
        open={editMemberModalVisible}
        onCancel={() => {
          setEditMemberModalVisible(false);
          setEditingMember(null);
          editMemberForm.resetFields();
        }}
        footer={null}
      >
        <Form
          form={editMemberForm}
          layout="vertical"
          onFinish={handleUpdateMemberRole}
        >
          <Form.Item>
            <Text>成员：{editingMember?.name}</Text>
          </Form.Item>

          <Form.Item
            label="新角色"
            name="role"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="请选择角色">
              <Option value="PL">PL</Option>
              <Option value="SE">SE</Option>
              <Option value="MDE">MDE</Option>
            </Select>
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button
                onClick={() => {
                  setEditMemberModalVisible(false);
                  setEditingMember(null);
                  editMemberForm.resetFields();
                }}
              >
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定修改
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TeamDetailPage;